package com.ionehe.group.common.uaa.ex.domain.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.convert.FunctionConvert;
import com.ionehe.group.common.uaa.ex.dao.FunctionDao;
import com.ionehe.group.common.uaa.ex.dao.SetMealFunctionDao;
import com.ionehe.group.common.uaa.ex.domain.service.FunctionReadService;
import com.ionehe.group.common.uaa.ex.dto.ForestNodeMerger;
import com.ionehe.group.common.uaa.ex.dto.FunctionDTO;
import com.ionehe.group.common.uaa.ex.dto.Paging;
import com.ionehe.group.common.uaa.ex.enums.ErrorMessages;
import com.ionehe.group.common.uaa.ex.enums.FunctionStatus;
import com.ionehe.group.common.uaa.ex.enums.FunctionType;
import com.ionehe.group.common.uaa.ex.model.UaaFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Copyright (c) 2020 ionehe.com
 * Date: 2020/11/25
 * Time: 10:31 上午
 *
 * @author 2020年 <a href="mailto:a@ionehe.com">秀</a>
 */
@Service
@Slf4j
public class FunctionReadServiceImpl implements FunctionReadService {
    @Resource
    private FunctionDao functionDao;
    @Resource
    private SetMealFunctionDao setMealFunctionDao;

    @Autowired(required = false)
    private FunctionConvert functionConvert;

    @Override
    public Response<List<FunctionDTO>> functionDetailInfo() {
        log.info("FunctionReadService[]functionDetailInfo[]start!");
        try {
            // 所有功能
            Example example = new Example(UaaFunction.class);
            example.createCriteria()
                    .andEqualTo("isDelete", false)
                    .andIn("type", Lists.newArrayList(FunctionType.DIREC.getValue(), FunctionType.MENU.getValue(), FunctionType.BUTTON.getValue()));
            List<UaaFunction> functions = functionDao.selectByExample(example);
            if (CollUtil.isEmpty(functions)) {
                return Response.yes(Collections.emptyList());
            }

            // 递归封装树
            return Response.yes(ForestNodeMerger.merge(functionConvert.do2dto(functions)));
        } catch (Exception e) {
            log.error("FunctionReadService[]functionDetailInfo[]error! cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no(ErrorMessages.GET_FUNCTION_LIST_FAIL.toString());
        }
    }

    @Override
    public Response<Paging<FunctionDTO>> pageFunctionDetailInfo(Integer pageNum, Integer pageSize) {
        log.info("FunctionReadService[]pageFunctionDetailInfo[]start!");
        try {
            // 所有功能
            UaaFunction f = new UaaFunction();
            f.setIsDelete(false);
            Page<Object> page = PageMethod.startPage(pageNum, pageSize);
            List<UaaFunction> functions = functionDao.select(f);
            if (CollUtil.isEmpty(functions)) {
                return Response.yes(Paging.empty());
            }

            Paging<FunctionDTO> paging = new Paging<>(page.getTotal(), ForestNodeMerger.merge(functionConvert.do2dto(functions)));
            return Response.yes(paging);
        } catch (Exception e) {
            log.error("FunctionReadService[]pageFunctionDetailInfo[]error! cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no(ErrorMessages.GET_FUNCTION_LIST_FAIL.toString());
        }
    }

    /**
     * 批量查询
     *
     * @param idList 需要更新的id集合
     * @return 查询结果集合
     */
    @Override
    public Response<List<FunctionDTO>> selectByIdList(List<Long> idList) {
        // 功能列表
        Example example = new Example(UaaFunction.class);
        example.createCriteria().andIn("id", idList);
        List<UaaFunction> functionList = functionDao.selectByExample(example);
        return Response.yes(functionConvert.do2dto(functionList));
    }

    @Override
    public Response<List<FunctionDTO>> listAll() {
        Example example = new Example(UaaFunction.class);
        example.createCriteria()
                .andEqualTo("status", FunctionStatus.ON_SHELF.getValue())
                .andEqualTo("isDelete", false);
        List<UaaFunction> functionDTOList = functionDao.selectByExample(example);
        functionDTOList = functionDTOList.stream().filter(f -> StrUtil.isNotBlank(f.getUrl())).collect(Collectors.toList());

        return Response.yes(functionConvert.do2dto(functionDTOList));
    }

    @Override
    public Response<List<FunctionDTO>> addSetMealFunctionList(Long setMealId) {
        log.info("FunctionReadService[]functionDetailInfo[]start!");
        try {
            // 查询该套餐下所有功能
            List<Long> functionIds = null;
            if (Objects.nonNull(setMealId)) {
                functionIds = setMealFunctionDao.selectFunctionIdsBysetMealId(setMealId);
            }
            // 所有功能
            UaaFunction f = new UaaFunction();
            f.setIsDelete(false);
            Example example = new Example(UaaFunction.class);
            Example.Criteria criteria = example.createCriteria();
            if (CollUtil.isNotEmpty(functionIds)) {
                criteria.andIn("id", functionIds);
            }
            criteria
                    .andEqualTo("isDelete", false)
                    .andEqualTo("status", 1)
                    .andIn("type", Lists.newArrayList(FunctionType.DIREC.getValue(), FunctionType.MENU.getValue(), FunctionType.BUTTON.getValue()));
            List<UaaFunction> functions = functionDao.selectByExample(example);
            if (CollUtil.isEmpty(functions)) {
                return Response.yes(Collections.emptyList());
            }

            return Response.yes(ForestNodeMerger.merge(functionConvert.do2dto(functions)));
        } catch (Exception e) {
            log.error("FunctionReadService[]functionDetailInfo[]error! cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no(ErrorMessages.GET_FUNCTION_LIST_FAIL.toString());
        }
    }

    @Override
    public Response<List<FunctionDTO>> setMealDetailFunctionList(Long id) {
        log.info("FunctionReadService[]functionDetailInfo[]start!");
        try {
            // 查询该套餐下所有功能
            List<Long> functionIds = setMealFunctionDao.selectFunctionIdsBysetMealId(id);
            // 所有功能
            UaaFunction f = new UaaFunction();
            f.setIsDelete(false);
            Example example = new Example(UaaFunction.class);
            example.createCriteria()
                    .andEqualTo("isDelete", false)
                    .andIn("type", Lists.newArrayList(FunctionType.DIREC.getValue(), FunctionType.MENU.getValue(), FunctionType.BUTTON.getValue()))
                    .andIn("id", functionIds);
            List<UaaFunction> functions = functionDao.selectByExample(example);
            if (CollUtil.isEmpty(functions)) {
                return Response.yes(Collections.emptyList());
            }

            return Response.yes(ForestNodeMerger.merge(functionConvert.do2dto(functions)));
        } catch (Exception e) {
            log.error("FunctionReadService[]functionDetailInfo[]error! cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no(ErrorMessages.GET_FUNCTION_LIST_FAIL.toString());
        }
    }
}
